#!/bin/bash

cd `dirname $0`

# options passed by cli
#       -f = tail -f, default 0
#       -r = restart, kill older process, default 1  ====> 效果不行
#       -b = build, default 0
#   -m msg = 测试专用
# 典型用法 ./run_jar.sh
#         ./run.sh -b
opt_build=0
opt_log=1
opt_restart=1

while getopts :rfbm: opt; do
  case "$opt" in
    b) opt_build=1 ;;
    f) opt_log=1 ;;
    r) opt_restart=1 ;;
    *)  echo "unkonwn option" ;;
  esac
done

echo "opt_build=$opt_build"
echo "opt_restart=$opt_restart"
echo "opt_log=$opt_log"

pname="eureka"
pid=`jps | awk -v name="$pname" '$0 ~ name {print $1}'`
if [ -n "$pid" ]; then
    kill -9 $pid
    sleep 1
fi

# 使用mvn命令很慢
#jar_file=$(mvn -q \
#    -Dexec.executable=echo \
#    -Dexec.args='${project.artifactId}-${project.version}.jar' \
#    --non-recursive \
#    exec:exec)
artifactId=$(xmllint --xpath "//*[local-name()='project']/*[local-name()='artifactId']/text()" pom.xml)
version=$(xmllint --xpath "//*[local-name()='project']/*[local-name()='version']/text()" pom.xml)
jar_file=$artifactId-$version.jar
mem_sz=300m # 250 ~ 4G

if [ "1" == "$opt_build" ]; then
    echo "build"
    mvn clean package -U -Dmaven.test.skip=true
fi

#rm -f nohup.out &>/dev/null
truncate -s0 nohup.out
echo "now run jar"
nohup \
java \
    -Xmx$mem_sz -Xms$mem_sz \
    -Djava.security.egd=file:/dev/./urandom \
    -Duser.timezone=Asia/Shanghai \
    -jar "$PWD/target/$jar_file" --spring.profiles.active=prod \
> nohup.out 2>&1 & # echo &! > my.pid # 无效

# 以下方式无效 
# echo &! > my.pid
# echo "pid="`cat my.pid`

if [ "1" == "$opt_log" ]; then
    tail -f nohup.out
fi